﻿using DlutOneKey.Controls;
using DlutOneKey.Web;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;

namespace DlutOneKey
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        Operations operations = new Operations();
        private CancellationTokenSource _autoSelectCts;
        public MainWindow()
        {
            InitializeComponent();
            MessageBox.Show("欢迎使用DLUT One Key一键选课软件！\n" +
                "使用前请认真阅读以下说明：\n" +
                "1.本软件原理为自动点击页面元素来实现自动选课，因此无法适配网页页面的实时变化。使用过程中必须有人值守。软件开发者对可能的误操作造成使用者的任何损失不负任何责任。\n" +
                "2.软件使用前必须已知对应课程的教学班代码，才能正常使用本软件进行选课。教学班代码可在全校开课查询功能中查询。\n" +
                "3.软件启动时会自动打开教务系统的登录页面，请在登录成功并进入选课页面后关闭所有其他标签页，以防软件出错。\n" +
                "4.软件提供了手动一键选课和自动按顺序选课两种自动选课方式。如果需要使用自动按顺序选课，请在使用软件前，先按您偏好的顺序排列好教学班代码的顺序，在进行选课时会严格按照您排序的顺序进行依次尝试选课。\n" +
                "5.由于软件在运行自动按顺序选课模式时，尝试选课速度较快，在进行多次尝试选课后，系统会提示操作过快，此时需要手动关闭提示窗口，方可继续进行自动选课。\n" +
                "祝您使用愉快！", "欢迎", MessageBoxButton.OK);
        }
        public Operations Operations
        {
            get { return operations; }
        }
        private void About_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("DLUT OneKey\nBy zhchmmx", "关于", MessageBoxButton.OK, MessageBoxImage.Information);
        }

        private void Import_Click(object sender, RoutedEventArgs e)
        {
            var openFileDialog = new Microsoft.Win32.OpenFileDialog
            {
                Filter = "文本文件 (*.txt)|*.txt",
                Title = "导入文本文件"
            };
            if (openFileDialog.ShowDialog() == true)
            {
                TabItem tabItem = new TabItem();
                tabItem.Header = System.IO.Path.GetFileName(openFileDialog.FileName);
                ScrollViewer scrollViewer = new ScrollViewer();
                StackPanel stackPanel = new StackPanel();
                scrollViewer.Content = stackPanel;
                string filePath = openFileDialog.FileName;
                var ClassIds = new List<string>();
                try
                {
                    foreach (var line in System.IO.File.ReadLines(filePath, Encoding.UTF8))
                    {
                        if (!string.IsNullOrWhiteSpace(line))
                        {
                            ClassIds.Add(line);
                            
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"读取文件时出错: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                foreach (var item in ClassIds)
                {
                    stackPanel.Children.Add(new Controls.ClassItem(item));
                }

                tabItem.Content = scrollViewer;
                MainTab.Items.Add(tabItem);
                MainTab.SelectedItem = tabItem;
            }
        }

        private async void StartAutoSelection_Click(object sender, RoutedEventArgs e)
        {
            _autoSelectCts = new CancellationTokenSource();
            for (int i = 0; i < MainTab.Items.Count; i++)
            {
                try
                {
                    await Web.AutoSelect.StartAutoSelect(operations, GetCurrentClassIds(), _autoSelectCts.Token);
                }
                catch (OperationCanceledException)
                {
                    Console.WriteLine("已跳过当前课程选课。");
                    break;
                }
                MainTab.SelectedIndex = MainTab.SelectedIndex + 1;
                if (_autoSelectCts.Token.IsCancellationRequested)
                    break;
            }
        }

        private List<string> GetCurrentClassIds()
        {
            List<string> classIds = new List<string>();
            try
            {
                TabItem selectedTab = MainTab.SelectedItem as TabItem;
                ScrollViewer scrollViewer = selectedTab.Content as ScrollViewer;
                StackPanel stackPanel = scrollViewer.Content as StackPanel;
                foreach (var item in stackPanel.Children)
                {
                    ClassItem classItem = item as ClassItem;
                    classIds.Add(classItem.ClassIdTextBox.Text);
                }
                return classIds;
            }
            catch (Exception e)
            {
                MessageBox.Show("请先导入教学班代码列表。");
                Console.WriteLine(e);
                return classIds;
            }

        }

        private void StopAutoSelection_Click(object sender, RoutedEventArgs e)
        {
            if (_autoSelectCts != null && !_autoSelectCts.IsCancellationRequested)
            {
                _autoSelectCts.Cancel();
                Console.WriteLine("已跳过当前课程选课。");
            }
        }
    }
}